/*
Copyright 2009 David Revell

This file is part of SwiFTP.

SwiFTP is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

SwiFTP is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with SwiFTP.  If not, see <http://www.gnu.org/licenses/>.
*/

package lfr.ustc.ftp;

import java.io.File;
import java.lang.reflect.Constructor;

public abstract class CmdManager implements Runnable {
	protected SocketManager sessionThread;

	protected static CmdMap[] cmdClasses = {
			new CmdMap("USER", CmdUSER.class),
			new CmdMap("PASS", CmdPASS.class),
			new CmdMap("OPTS", CmdOPTS.class),
			new CmdMap("PWD", CmdPWD.class),
			new CmdMap("TYPE", CmdTYPE.class),
			new CmdMap("SYST", CmdSYST.class),
			new CmdMap("NOOP", CmdNOOP.class),
			new CmdMap("CWD", CmdCWD.class),
			new CmdMap("PORT", CmdPORT.class),
			new CmdMap("PASV", CmdPASV.class),
			new CmdMap("SIZE", CmdSIZE.class),
			new CmdMap("LIST", CmdLIST.class),
			new CmdMap("RETR", CmdRETR.class),
			new CmdMap("NLST", CmdNLST.class),
			new CmdMap("QUIT", CmdQUIT.class),
			new CmdMap("NLST", CmdNLST.class),
			new CmdMap("RMD", CmdRMD.class),
			new CmdMap("STOR", CmdSTOR.class),
			new CmdMap("DELE", CmdDELE.class),
			new CmdMap("RNFR", CmdRNFR.class),
			new CmdMap("XMKD", CmdMKD.class),
			new CmdMap("RNTO", CmdRNTO.class),
			new CmdMap("MKD", CmdMKD.class),
			new CmdMap("FEAT", CmdFEAT.class),
			new CmdMap("CDUP", CmdCDUP.class),
			new CmdMap("XPWD", CmdPWD.class),
			new CmdMap("APPE", CmdAPPE.class),
			new CmdMap("XCUP", CmdCDUP.class),
			new CmdMap("XRMD", CmdRMD.class) };

	public CmdManager(SocketManager sessionThread) {
		this.sessionThread = sessionThread;
	}

	abstract public void run();

	protected static void dispatchCommand(SocketManager socketUtil,
			String inputString) {
			String[] strings = inputString.split(" ");
		   String unrecognizedCmdMsg = "502 Command not recognized\r\n";
		if (strings == null) {
			String errString = "502 Command parse error\r\n";
			socketUtil.sendInfo(errString);
			return;
		}
		if (strings.length < 1) {
			socketUtil.sendInfo(unrecognizedCmdMsg);
			return;
		}
		String verb = strings[0];
		if (verb.length() < 1) {
			socketUtil.sendInfo(unrecognizedCmdMsg);
			return;
		}
		CmdManager cmdInstance = null;
		verb = verb.trim();
		verb = verb.toUpperCase();
		for (int i = 0; i < cmdClasses.length; i++) {

			if (cmdClasses[i].getName().equals(verb)) {
				Constructor<? extends CmdManager> constructor;
				try {
					constructor = cmdClasses[i].getCommand().getConstructor(
							new Class[] { SocketManager.class, String.class });
				} catch (NoSuchMethodException e) {

					return;
				}
				try {
					cmdInstance = constructor.newInstance(new Object[] {
							socketUtil, inputString });
				} catch (Exception e) {

					return;
				}
			}
		}
		if (cmdInstance == null) {
			socketUtil.sendInfo(unrecognizedCmdMsg);
			return;
		} else if (socketUtil.isLogin
				|| cmdInstance.getClass().equals(CmdUSER.class)
				|| cmdInstance.getClass().equals(CmdPASS.class)
				|| cmdInstance.getClass().equals(CmdUSER.class)) {
			cmdInstance.run();
		} else {
			socketUtil.sendInfo("530 Login first with USER and PASS\r\n");
		}
	}

	static public String getParameter(String input) {
		if (input == null) {
			return "";
		}
		int firstSpacePosition = input.indexOf(' ');
		if (firstSpacePosition == -1) {
			return "";
		}
		String retString = input.substring(firstSpacePosition + 1);

		retString = retString.replaceAll("\\s+$", "");

		return retString;
	}

	public static File inputPathToChrootedFile(File existingPrefix, String param) {
		try {
			if (param.charAt(0) == '/') {
				File chroot = CommonSettings.getChrootDir();
				return new File(chroot, param);
			}
		} catch (Exception e) {
		}

		return new File(existingPrefix, param);
	}

	public boolean violatesChroot(File file) {
		File chroot = CommonSettings.getChrootDir();
		try {
			String canonicalPath = file.getCanonicalPath();
			if (!canonicalPath.startsWith(chroot.toString())) {
				return true;
			}
			return false;
		} catch (Exception e) {
			return true;
		}
	}
}
